package org.budo.support.java.awt.image.util;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
public class BufferedImageUtil {
    /**
     * 如果位置超过图像范围，就返回0
     */
    public static int getRGB_0(BufferedImage image, int x, int y) {
        if (null == image || x < 0 || y < 0) {
            return 0;
        }

        int w = image.getWidth();
        int h = image.getHeight();

        if (x > w || y > h) {
            return 0;
        }

        return image.getRGB(x, y);
    }

    public static int getRGB(BufferedImage image, int x, int y) {
        if (null == image || x < 0 || y < 0) {
            throw new RuntimeException("#13 x=" + x + ", y=" + y + ", image=" + image);
        }

        try {
            return image.getRGB(x, y);
        } catch (ArrayIndexOutOfBoundsException e) {
            int w = image.getWidth();
            int h = image.getHeight();
            throw new RuntimeException("#21 x=" + x + ", y=" + y + ", w=" + w + ", h=" + h + ", e=" + e, e);
        }
    }

    public static BufferedImage getSubimage(BufferedImage bufferedImage, int x, int y, int w, int h) {
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        if (x > width || y > height || x < 0 || y < 0) {
            throw new IllegalArgumentException("#95 x=" + x + ", y=" + y + ", width=" + width + ", height=" + height);
        }

        int w_1 = w;
        if (x + w > width) {
            w_1 = width - x;
        }

        int h_1 = h;
        if (y + h > height) {
            h_1 = height - y;
        }

        if (w_1 < 1 || h_1 < 1) {
            log.error("#139 w_1=" + w_1 + ", h_1=" + h_1 + ", x=" + x + ", y=" + y + ", w=" + w + ", h=" + h + ", width=" + width + ", height=" + height);
            return null;
        }

        try {
            BufferedImage subImg = bufferedImage.getSubimage(x, y, w_1, h_1);
            return subImg; // 返回子图
        } catch (Throwable e) {
            throw new RuntimeException("#130 x=" + x + ", y=" + y + ", w=" + w + ", h=" + h //
                    + ", w_1=" + w_1 + ", h_1=" + h_1 + ", width=" + width + ", height=" + height //
                    + ", e=" + e, e);
        }
    }

    public static BufferedImage getSubimage(BufferedImage bufferedImage, Rectangle rectangle) {
        int x = (int) rectangle.getX();
        int y = (int) rectangle.getY();
        int width = (int) rectangle.getWidth();
        int height = (int) rectangle.getHeight();

        return getSubimage(bufferedImage, x, y, width, height);
    }
}